$(document).ready(function () {

    var page = 0;
    var len = 20;

    var loc;

    var g = new BMap.Geolocation();
    g.getCurrentPosition(function(r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            loc =  r.point.lng + "," + r.point.lat;
            initShopListPage();
        } else {
            loc = "117.217784,39.144832";
            initShopListPage();
        }
    });

    //if (navigator.geolocation) {
    //    navigator.geolocation.getCurrentPosition(showPosition);
    //} else {
    //    showPositionError();
    //}

    //function showPosition(res) {
    //    console.log(g.getStatus());
    //    //JSON.stringify(res);
    //    /*
    //    loc = "" + position.coords.latitude + "," + position.coords.longitude;
    //    initShopListPage();
    //    */
    //}

    function showPositionError() {
        loc = "117.217784,39.144832";
        initShopListPage();
    }

    function initShopListPage() {
        console.log(loc);

        loadShopList();

        $(window).scroll(function(){
            if($(window).scrollTop() == $(document).height() - $(window).height()){
                page ++;
                loadShopList();
            }
        });
    }

    function loadShopList() {
        /* 百度地图ajax对象 */
        var lbs = {
            ak: "wFPFZHW4pchcuUGeLxGgWwq4",
            geotable_id: 95394,
            sortby: "distance:1",
            location: loc,
            radius: 1000000,
            tags: ""+ type,
            page_size: len,
            page_index: page
        };

        $.ajax({
            dataType: "JSONP",
            type: "GET",
            data: lbs,
            url: "http://api.map.baidu.com/geosearch/v3/nearby",
            success: function (data) {
                if (data.status != 0) {
                    alert("获取失败");
                    return;
                }

                var render = _.template($("#tmpl").html());
                var str = "";
                _.each(data.contents, function (d) {
                    str += render(d);
                });
                $("ul").append(str);
            }
        });
    };
});